package com.rachel.studyapp.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.rachel.studyapp.R;
import com.rachel.studyapp.activity.BaseActivity;
import com.rachel.studyapp.activity.LoginActivity;
import com.rachel.studyapp.activity.MainActivity;
import com.rachel.studyapp.activity.PermissionCallback;
import com.rachel.studyapp.adapter.CommonAdapter;
import com.rachel.studyapp.adapter.CustomPopupWindow;
import com.rachel.studyapp.adapter.LBaseViewholder;
import com.rachel.studyapp.mvp.base.BasePresent;
import com.rachel.studyapp.utils.BitmapUtils;
import com.rachel.studyapp.utils.SPUtils;
import com.rachel.studyapp.utils.ToolUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zhengshaorui on 2017/5/23.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private static final String TAG = "zsr";
    private static final int CUT_CAMERA = 1;
    /**
     * ui
     */
    private CircleImageView mUserLogoIcon;
    private TextView mUserLoginname;
    private TextView mUserLoginStatus;
    private TextView mUserName;
    private View mMineView;
    private ListView mListView;
    private Button mExitLogin;
    /**
     * data
     */
    private Uri mCutUri;
    private MainActivity mActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mMineView == null) {
            mActivity = (MainActivity) getActivity();
            mMineView = inflater.inflate(R.layout.fragment_my, container, false);
            initView(mMineView);
            ImmersionBar.with(this).fullScreen(true).init();
            EventBus.getDefault().register(this);
            boolean isexit = SPUtils.getBooleanData(ToolUtils.USERNAME,ToolUtils.LOGIN);
            Log.d(TAG, "onCreateView: "+isexit);
            if (isexit) {
                String username = SPUtils.getStringData(ToolUtils.SPNAME, ToolUtils.USERNAME);
                if (username != null) {
                    loginSuccessOrlogined(username);
                }
            }
        }
        return mMineView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void loginSuccess(String username){
        loginSuccessOrlogined(username);
    }

    /**
     * 登陆成功或者已经登陆过后，改变控件的位置
     * @param username
     */
    private void loginSuccessOrlogined(String username) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mUserLogoIcon.getLayoutParams();
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        mUserLogoIcon.setLayoutParams(params);

        mUserLoginname.setVisibility(View.GONE);
        mUserLoginStatus.setVisibility(View.GONE);
        mUserName.setVisibility(View.VISIBLE);
        mUserName.setText(username);
        SPUtils.saveBooleanData(ToolUtils.USERNAME,ToolUtils.LOGIN,true);
        mExitLogin.setVisibility(View.VISIBLE);
    }

    private void initView(View view) {
        mUserLogoIcon = (CircleImageView) view.findViewById(R.id.user_login_icon);
        mUserLogoIcon.setOnClickListener(this);
        mUserLoginname = (TextView) view.findViewById(R.id.user_login_name);
        String path = SPUtils.getStringData(ToolUtils.USERNAME,ToolUtils.USERICON);


        mUserLoginStatus = (TextView) view.findViewById(R.id.user_login_status);
        mUserLoginStatus.setOnClickListener(this);
        mUserName = (TextView) view.findViewById(R.id.login_name);

        mListView = (ListView) view.findViewById(R.id.mine_listview);

        List<String> lists = new ArrayList<>();
        lists.add("关于我");
        lists.add("分享该app给朋友");
        lists.add("检查更新");

        CommonAdapter<String> adapter = new CommonAdapter<String>(mActivity,lists,R.layout.listview_item_mine) {
            @Override
            public void convert(LBaseViewholder viewHolder, String data) {

                viewHolder.setText(R.id.item_mine_text,data);
            }



        };
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);


        mExitLogin = (Button) view.findViewById(R.id.mine_exit);
        mExitLogin.setOnClickListener(this);

        boolean isexit = SPUtils.getBooleanData(ToolUtils.USERNAME,ToolUtils.LOGIN);
        if (isexit) {
            if (path != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                if (bitmap != null) {
                    mUserLogoIcon.setImageBitmap(bitmap);
                }else{
                    mUserLogoIcon.setImageResource(R.mipmap.beauty);
                }
            } else {
                mUserLogoIcon.setImageResource(R.mipmap.beauty);
            }
        }else{
            mExitLogin.setVisibility(View.GONE);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_login_icon:
                showBottomPop();

                break;
            case R.id.user_login_status:
                startActivityForResult(new Intent(mActivity, LoginActivity.class),1);
                break;
            case R.id.mine_exit:
                exitLogin();
                break;
        }
    }


    /**
     * 退出登陆
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void exitLogin() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mUserLogoIcon.getLayoutParams();
        params.setMargins(ToolUtils.dip2px(mActivity,50),
                ToolUtils.dip2px(mActivity,50),
                0,
                0);
        params.removeRule(RelativeLayout.CENTER_IN_PARENT);
        mUserLogoIcon.setLayoutParams(params);
        mUserLogoIcon.setImageResource(R.mipmap.beauty);
        mUserLoginname.setVisibility(View.VISIBLE);
        mUserLoginStatus.setVisibility(View.VISIBLE);
        mUserName.setVisibility(View.GONE);
        mExitLogin.setVisibility(View.GONE);
        SPUtils.saveBooleanData(ToolUtils.USERNAME,ToolUtils.LOGIN,false);
        String path = SPUtils.getStringData(ToolUtils.USERNAME,ToolUtils.USERICON);
        if (path != null){
            File file = new File(path);
            file.delete();
        }
    }
    /**
     * 点击头像，弹出图片对话框
     */
    private void showBottomPop() {
        final CustomPopupWindow popupWindow = new CustomPopupWindow.Builder()
                .setContext(mActivity)
                .setContentView(R.layout.popupwind_image_choose)
                .setFouse(true)
                .setOutSideCancel(true)
                .setBackGroudAlpha(mActivity,0.7f)
                .setAnimationStyle(R.style.popup_tanslation)
                .builder()
                .showAtLocation(R.layout.fragment_my,
                        Gravity.BOTTOM,0,0);
        //取消
        popupWindow.setOnClickListener(R.id.pop_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //相册
        popupWindow.setOnClickListener(R.id.pop_pic, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();
                BaseActivity.checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        new PermissionCallback() {
                            @Override
                            public void onGranted() {
                                /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.setType("image*//**//*");
                                startActivityForResult(intent,ToolUtils.SCAN_OPEN_PHONE);*/
                                //由于模拟器图库的刷新问题，采用如下打开方式，实际开发请采用上面这种
                                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent, ToolUtils.SCAN_OPEN_PHONE);
                            }

                            @Override
                            public void onDenied(List<String> deniedPermissions) {
                                Toast.makeText(mActivity, "相册打开失败", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });
        popupWindow.setOnClickListener(R.id.pop_camera, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                BaseActivity.checkPermissions(new String[]{Manifest.permission.CAMERA},
                        new PermissionCallback() {
                            @Override
                            public void onGranted() {
                                BitmapUtils.openCamera(mActivity,MineFragment.this);
                            }
                            @Override
                            public void onDenied(List<String> deniedPermissions) {
                                Toast.makeText(mActivity, "相册打开失败", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case ToolUtils.SCAN_OPEN_PHONE: //从相册图片后返回的uri
                    //启动裁剪
                    mCutUri = BitmapUtils.CutForPhoto(data.getData(),mActivity,this);

                    break;
                case ToolUtils.PHONE_CAMERA: //相机返回的 uri
                    //启动裁剪
                   mCutUri = BitmapUtils.CutForCamera(mActivity,this);
                    break;
                case ToolUtils.PHONE_CROP:
                    Log.d(TAG, "PHONE_CROP: "+mCutUri);

                    String imgpath = BitmapUtils.UriTranslationPath(mActivity,mCutUri);
                    if (imgpath != null) {
                        Bitmap bitmap = BitmapFactory.decodeFile(imgpath);
                        mUserLogoIcon.setImageBitmap(bitmap);
                        SPUtils.saveStringData(ToolUtils.USERNAME,ToolUtils.USERICON,imgpath);
                    }

                    break;
            }
        }
    }




    @Override
    public BasePresent initPresent() {
        return null;
    }

    @Override
    public void onFailure(Object errorObj) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0){ //about me
            CustomPopupWindow popupWindow = new CustomPopupWindow.Builder()
                    .setContext(mActivity)
                    .setwidth(ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setheight(ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setContentView(R.layout.popupwindow_aboutme)
                    .setOutSideCancel(true)
                    .setFouse(true)
                    .setAnimationStyle(R.style.popup_anmi)
                    .setBackGroudAlpha(mActivity,0.5f)
                    .builder()
                    .showAtLocation(R.layout.fragment_my,Gravity.CENTER,0,0);
            TextView text = (TextView) popupWindow.getItemView(R.id.pop_about_blog);
            text.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}
